package com.hohai.river.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hohai.river.entity.Score;
import com.hohai.river.entity.SysIndex;
import com.hohai.river.mapper.ScoreMapper;
import com.hohai.river.service.ScoreService;
import com.hohai.river.service.SysIndexService;
import com.hohai.river.utils.JsonUtils;
import com.pig4cloud.pig.admin.api.feign.RemoteFileService;
import feign.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分数表
 */
@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {

	@Lazy
	@Autowired
	private SysIndexService sysIndexService;

	@Resource
	private RemoteFileService remoteFileService;

	@Override
	public Score getScore(Long riverId, Long indexId) {
		LambdaQueryWrapper<Score> query = new LambdaQueryWrapper<>();
		query.eq(Score::getRiverId, riverId).eq(Score::getIndexId, indexId);
		return this.baseMapper.selectOne(query);
	}

	@Override
	public List<Score> getIndexFinishedNormal(Long riverId) {
		LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(Score::getRiverId, riverId);
		return this.baseMapper.selectList(wrapper);
	}

	@Override
	public List<Score> getIndexFinishedExpert(Long riverId, String expertId) {
		LambdaQueryWrapper<Score> query = new LambdaQueryWrapper<>();
		query.eq(Score::getRiverId, riverId);
		return this.baseMapper.selectList(query).stream().filter(score -> !StringUtils.isEmpty(score.getExpertList())
				&& JSON.parseObject(score.getExpertList()).containsKey(expertId)).collect(Collectors.toList());
	}

	@Override
	public List<Map> calculateTotalScore(Long riverId) {

		return this.baseMapper.calculateTotalScore(riverId).stream()
				.sorted(Comparator.comparing(item -> ((String) item.get("index_name")))).collect(Collectors.toList());
	}

	@Override
	public List<Map<String, Object>> getMaxScore(Integer level) {
		List<SysIndex> list = sysIndexService.list(Wrappers.<SysIndex>lambdaQuery().select(SysIndex::getId,
				SysIndex::getIndexCode, SysIndex::getPid, SysIndex::getIndexName));
		// indexCode对应的pid
		Map<String, Long> pidMap = new HashMap<>();
		// pid对应的name
		Map<Long, String> nameMap = new HashMap<>();
		list.forEach(item -> {
			if (StringUtils.isNotEmpty(item.getIndexCode())) {
				pidMap.put(item.getIndexCode(), item.getPid());
			}
			else {
				nameMap.put(item.getId(), item.getIndexName());
			}
		});
		nameMap.put(-1L, "满意度调查");

		Map<String, Integer> map = new HashMap<>();
		Response response = remoteFileService.file(JsonUtils.BUCKET, JsonUtils.FILE_NAME);
		JSONObject jsonObject = JsonUtils.getJsonObjectFromResponse(response);
		jsonObject.keySet().forEach(key -> {
			String indexCode = key.substring(0, key.length() - 5);
			if (pidMap.get(indexCode) != null) {
				String indexName = nameMap.get(pidMap.get(indexCode));
				Integer val = map.getOrDefault(indexName, 0);

				JSONArray array = jsonObject.getJSONObject(key).getJSONArray(level.toString());
				val += array.getInteger(0);
				map.put(indexName, val);
			}
		});

		List<Map<String, Object>> res = new ArrayList<>();
		map.keySet().forEach(key -> {
			Map<String, Object> resMap = new HashMap<>();
			resMap.put("name", key);
			resMap.put("max", map.get(key));
			res.add(resMap);
		});
		return res.stream().sorted(Comparator.comparing(item -> ((String) item.get("name"))))
				.collect(Collectors.toList());
	}

}
